package com.example.romancalc;

import org.apache.log4j.Logger;

import com.example.romancalc.core.RomanNumeralException;
import com.example.romancalc.core.RomanNumber;
import com.vaadin.data.Validator;

public class RomanNumberValidator implements Validator {

	/**
	 * 
	 */
	private static final long serialVersionUID = -5834387086813290197L;

	private static final Logger logger = Logger
			.getLogger(RomanNumberValidator.class);

	private String message;

	public RomanNumberValidator(String message) {
		this.message = message;
	}

	public void validate(Object value) throws InvalidValueException {
		if (!isValid(value)) {
			throw new InvalidValueException(message);
		}
	}

	public boolean isValid(Object value) {
		if (value == null || !(value instanceof String)) {
			return false;
		}
		try {
			@SuppressWarnings("unused")
			RomanNumber rm = new RomanNumber((String) value);
		} catch (RomanNumeralException rnum) {
			logger.warn(String.format("Validation error for input: %s",
					rnum.getIllegalRomanNumber()));
			return false;
		} catch (Exception e) {
			return false;
		}
		return true;
	}

}
